package com.learner.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description: 连接搜索的客户端，工具类 注入高等和低等客户端
 * @Author: ice2020x
 * @Date: 2021/8/20
 */
@Configuration
public class ElasticsearchConfig {

    @Value("${learner.elasticsearch.hostlist}")
    private String hostList;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        //创建RestHighLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(analysisHostList()));
    }

    /**
     * 项目主要使用RestHighLevelClient，对于低级的客户端暂时不用
     */
    @Bean
    public RestClient restClient() {
        return RestClient.builder(analysisHostList()).build();
    }

    private HttpHost[] analysisHostList() {
        String[] split = hostList.split(",");
        //创建HttpHost数组，其中存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String item = split[i];
            String hostname = item.split(":")[0];
            int port = Integer.parseInt(item.split(":")[1]);
            httpHostArray[i] = new HttpHost(hostname, port, "http");
        }
        return httpHostArray;
    }

}
